package org.training.gl.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang.Validate;
import org.training.gl.xml.generated.Catalog;

public class JaxbHelper {

	public static String toXml(Catalog catalog) throws JAXBException {
		Validate.notNull(catalog, "Catalog is null");

		JAXBContext context = JAXBContext.newInstance(Catalog.class);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		StringWriter stringWriter = new StringWriter();
		marshaller.marshal(catalog, stringWriter);
		return stringWriter.toString();
	}

	public static void toXml(Catalog catalog, File file) throws JAXBException,
			IOException {
		Validate.notNull(catalog, "Catalog is null");
		Validate.notNull(file, "File is null");

		JAXBContext context = JAXBContext.newInstance(Catalog.class);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		FileWriter fileWriter = new FileWriter(file);
		marshaller.marshal(catalog, fileWriter);
		fileWriter.flush();
	}

	public static Catalog fromXml(String xml) throws JAXBException {
		Validate.notNull(xml, "String is null");

		JAXBContext context = JAXBContext.newInstance(Catalog.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		Object object = unmarshaller.unmarshal(new StringReader(xml));
		return (Catalog) object;
	}
	
	public static Catalog fromXml(InputStream is) throws JAXBException {
		Validate.notNull(is, "InputStream is null");

		JAXBContext context = JAXBContext.newInstance(Catalog.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		Object object = unmarshaller.unmarshal(new InputStreamReader(is));
		return (Catalog) object;
	}

	public static Catalog fromXml(File file) throws JAXBException {
		Validate.notNull(file, "File is null");

		JAXBContext context = JAXBContext.newInstance(Catalog.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		Object object = unmarshaller.unmarshal(file);
		return (Catalog) object;
	}
}
